import React, { useEffect, useState } from "react";
import '../proof.css';
import '../../../App.css'
import '../../Login/login.css';
import icon_contact_add from '@/assets/icon_contact_add.png'
import { useHistory, useLocation } from "react-router-dom/cjs/react-router-dom";
import { Mask, DotLoading, Toast } from "antd-mobile";
import { useDispatch } from "react-redux";
import { isActionInput, isActionSelect, isProofContact, isProofFace, isProofFrequentlyUsedApps, isProofMobile } from "@/store/actions/userState";
import { isEmptyString, isMustProofString, toTrimString } from "@/utils/utils";
import { PageTag } from "@/utils/pageTag";
import ProofNavigateBar from "@/components/ProofNavigateBar";
import { isLoanLoaning, isLoanReject, isLoanRepayNow, isLoanReviewing, isLoanSigning } from "@/utils/loanStatus";
import AddHomeEvent from "@/utils/addHomeEvent";
import PrivacyPolicyLink from "@/components/PrivacyPolicyLink/PrivacyPolicyLink";
import { reqSaveEvent, reqSaveProofContactData, reqUserState } from "@/store/actions/apiServices";
import FormSelect from "@/components/FormSelect";
import FormSelectContact from "@/components/FormSelect/formselectcontact";


export default function ProofContact() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false);
    const relationList = [
        {
            "label": "Couple",
            "value": "Couple"
        },
        {
            "label": "Father",
            "value": "Father"
        },
        {
            "label": "Mother",
            "value": "Mother"
        },
        {
            "label": "Children",
            "value": "Children"
        },
        {
            "label": "Brother",
            "value": "Brother"
        },
        {
            "label": "Sister",
            "value": "Sister"
        },
        {
            "label": "Grandparents",
            "value": "Grandparents"
        },
        {
            "label": "Colleagues",
            "value": "Colleagues"
        },
        {
            "label": "Relatives",
            "value": "Relatives"
        },
        {
            "label": "Classmates",
            "value": "Classmates"
        },
        {
            "label": "Others",
            "value": "Others"
        }
    ];
    const nameRow = {
        "title": "Name*",
        "hint": "Please select",
        "paramName": "fullName",
        "action": "CONTACT_GROUP_NAME",
        "content": "",
        "realContent": "",
        "showIcon": false,
        "pickValues": []
    };
    const phoneRow = {
        "title": "Phone Number*",
        "hint": "Please select",
        "paramName": "mobile",
        "action": "CONTACT_GROUP_PHONE",
        "content": "",
        "realContent": "",
        "showIcon": true,
        "pickValues": []
    };
    const relationRow = () => {
        return {
            "title": "Relationship*",
            "hint": "Please select",
            "paramName": "relation",
            "action": "CONTACT_GROUP_RELATION",
            "content": "",
            "realContent": "",
            "pickValues": [[...relationList]]
        }
    };
    const sectionItem = () => {
        const row1 = relationRow();
        return [
            { ...row1 },
            { ...nameRow },
            { ...phoneRow }
        ];
    };
    const sectionItemss = [
        {
            "title": "Relationship*",
            "hint": "Please select",
            "paramName": "relation",
            "action": "CONTACT_GROUP_RELATION",
            "content": "",
            "realContent": "",
            "pickValues": [[...relationList]]
        },
        {
            "title": "Name*",
            "hint": "Please enter",
            "paramName": "fullName",
            "action": "CONTACT_GROUP_NAME",
            "content": "",
            "realContent": "",
            "pickValues": []
        },
        {
            "title": "Phone Number*",
            "hint": "500 866 603",
            "paramName": "mobile",
            "action": "CONTACT_GROUP_PHONE",
            "content": "",
            "realContent": "",
            "pickValues": []
        }
    ];

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);
    const [sectionList, setSectionList] = useState([]);

    // 获取路由历史 history 对象
    const history = useHistory()

    // 获取路由信息 location 对象
    const location = useLocation()

    //获取 Redux 分发器
    const dispatch = useDispatch()

    //获取Redux Store中的用户状态信息
    const [userStateInfo, setUserStateInfo] = useState({});

    const onReqUserStateCallback = (success, resObj) => {
        setMaskVisible(false);
        if (success && resObj) {
            console.log("Launch-signOrderId: " + resObj.signOrderId);
            setUserStateInfo(resObj);

            //是否为签约中
            const isHomeSigning = isLoanSigning(resObj.signFlag, resObj.signOrderId);
            //是否为审核中
            const isHomeReviewing = isLoanReviewing(resObj.applyStatus);
            //是否为拒绝
            const isHomeReject = isLoanReject(resObj.applyStatus, resObj.orderStatus);
            //是否为放款中
            const isHomeLoaning = isLoanLoaning(resObj.orderStatus);
            //是否为待还款
            const isHomeRepay = isLoanRepayNow(resObj.orderStatus);
            //是否为待进件
            const isHomeNotLoan = ((!isHomeReviewing) && (!isHomeReject) && (!isHomeLoaning) && (!isHomeRepay));
            console.log("Launch-isHomeReviewing: " + isHomeReviewing);
            console.log("Launch-isHomeReject: " + isHomeReject);
            console.log("Launch-isHomeLoaning: " + isHomeLoaning);
            console.log("Launch-isHomeRepay: " + isHomeRepay);
            console.log("Launch-isHomeNotLoan: " + isHomeNotLoan);
            console.log("Launch-isHomeSigning: " + isHomeSigning);

            //跳转状态页
            if (isHomeSigning) {
                history.replace('/guide');
                return;

            } else if (isHomeReviewing) {
                history.replace('/review');
                return;

            } else if (isHomeReject) {
                history.replace('/reject');
                return;

            } else if (isHomeLoaning) {
                history.replace('/loaning');
                return;

            } else if (isHomeRepay) {
                history.replace('/repay');
                return;
            }

            //判断下是否已经做完所有认证
            if (resObj.isProofFinish === true) {
                //跳转申请页
                history.replace('/apply');
                return;
            }

            //是否为号码认证
            if (isProofMobile(resObj.stepTitle)) {
                history.replace('/proofmobile');
                return;
            }

            //是否为常用app认证
            if (isProofFrequentlyUsedApps(resObj.stepTitle)) {
                history.replace('/prooffrequentlyapps');
                return;
            }

            //是否为人脸认证
            if (isProofFace(resObj.stepTitle)) {
                history.replace('/proofface');
                return;
            }

            if (isProofContact(resObj.stepTitle)) {
                return;
            }

            history.replace('/proof');
        }
    };

    const checkUserStateInfo = async () => {
        try {
            setMaskVisible(true);
            reqUserState(PageTag.PROOF_CONTACT, onReqUserStateCallback);

        } catch (e) {
            console.log(e)
        }
    }

    const onHandleNavGoBack = () => {
        history.replace('/home');
    }

    const onHandleAddToHome = (type) => {
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    const onHandleAddToHomeClose = () => {
        setAddHomeMaskVisible(false)
    }

    const onHandleBlur = (index, value) => {
        console.log("onHandleBlur: " + index);
    }

    const onHandleInputChangeForContact = (parentIndex, index, value) => {
        try {
            const newState = [...sectionList];
            const section = newState[parentIndex];
            const item = section[index];
            item.content = value;
            item.realContent = value;
            setSectionList(newState);

        } catch (e) {
            console.log(e)
        }
    }

    const onHandleSelectedDataForContact = async (parentIndex, index, type, data) => {
        try {
            const newState = [...sectionList];
            const section = newState[parentIndex];
            const item = section[index];
            item.content = data.label;
            item.realContent = data.value;
            setSectionList(newState);
        } catch (e) {
            console.log(e)
        }
    }

    const onHandleShowContactPicker = async (parentIndex, index, type, data) => {
        try {
            const props = ['name', 'tel'];
            const opts = { multiple: false };
            const contacts = await navigator.contacts.select(props, opts);
            // const jsonString = JSON.stringify(contacts);
            // Toast.show(jsonString);
            // console.log(contacts);
            // [{
            //     "email": [],
            //     "name": ["Queen O'Hearts"],
            //     "tel": ["+1-206-555-1000", "+1-206-555-1111"]
            //   }]
            if (contacts && contacts.length > 0) {
                let contact0 = contacts[0];
                let uName = (contact0.name || []).join("#");
                let uPhone = (contact0.tel || []).join("#");

                if ((uName.length > 0) && (uPhone.length > 0)) {
                    const newState = [...sectionList];
                    const section = newState[parentIndex];
                    if (section.length > 2) {
                        const nameItem = section[1];
                        nameItem.content = uName;
                        nameItem.realContent = uName;

                        const phoneItem = section[2];
                        phoneItem.content = uPhone;
                        phoneItem.realContent = uPhone;
                        setSectionList(newState);
                    }
                }
            }
        } catch (e) {
            if (!e) {
                reqSaveEvent("CONTACT_PICKER_ERR");

                // Toast.show(e);
                history.replace('/proofcontactinput');
            }
        }
    }

    const onHandleMoreContact = () => {
        try {
            const newState = [...sectionList];
            let section1 = sectionItem();
            newState.push(section1);
            setSectionList(newState);

        } catch (e) {
            console.log(e)
        }
    }

    const onHandleSubmit = () => {
        //组装参数
        const params = {}

        //判断所有内容是否输入完成
        let sectionFinish = true
        sectionList.forEach(section => {
            section.forEach(item => {
                if (isMustProofString(item.isMust)) {
                    if (isEmptyString(item.realContent)) {
                        sectionFinish = false
                    }
                }
            })
        })

        if (!sectionFinish) {
            Toast.show("Please fill all contents.")
            return
        }

        const contactList = []
        sectionList.forEach(section => {
            const contact = {}
            section.forEach(item => {
                contact[item.paramName] = toTrimString(item.realContent + "")
            })
            contactList.push(contact)
        })
        params["contactList"] = contactList

        setMaskVisible(true);
        reqSaveProofContactData(params, (success, resObj) => {
            setMaskVisible(false);
            if (success) {
                reqUserState(PageTag.PROOF, onReqUserStateCallback);
            }
        });
    }

    const onHandleSupportContactApi = async () => {

        try {
            await navigator.contacts.getProperties();
        } catch {
            history.replace('/proofcontactinput');
        }
    };

    useEffect(() => {
        checkUserStateInfo()
        reqSaveEvent("PROOF_CONTACT_START")

        let section1 = sectionItem();
        let section2 = sectionItem();
        let newState = [];
        newState.push(section1);
        newState.push(section2);
        setSectionList(newState);

        onHandleSupportContactApi();

        return () => {
            reqSaveEvent("PROOF_CONTACT_END")
        }
    }, [])


    return (
        <div className="proofRoot">
            <ProofNavigateBar theme="white" onBackClick={onHandleNavGoBack} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{userStateInfo.pageTitle}</ProofNavigateBar>

            <div className="proofContent">
                {sectionList.map((value, index) => {
                    return (
                        <div className="contentColumnStart" key={index}>
                            <div className="proofEdgeTopMainBackground"></div>
                            <div className="proofSectionTitle">Emergency contact {index + 1}</div>
                            {(value.map((itemValue, itemIndex) => {
                                return (
                                    <div className="proofItemList" key={index + "_" + itemIndex}>
                                        {(isActionSelect(itemValue.action) === true) && <FormSelect
                                            placeholder={itemValue.hint}
                                            value={itemValue.content}
                                            title={itemValue.title}
                                            list={itemValue.pickValues}
                                            onSelectedDataClick={e => { onHandleSelectedDataForContact(index, itemIndex, itemValue.paramName, e) }}
                                            autoComplete="off" />}

                                        {(isActionInput(itemValue.action) === true) && <FormSelectContact
                                            placeholder={itemValue.hint}
                                            value={itemValue.content}
                                            title={itemValue.title}
                                            showIcon={itemValue.showIcon}
                                            onSelectedDataClick={() => { onHandleShowContactPicker(index, itemIndex, itemValue.paramName) }}
                                            autoComplete="off" />}
                                    </div>
                                )
                            }))}
                            <div className="proofEdgeTopWhite"></div>
                        </div>
                    )
                })}
            </div>

            <div className="proofAddMoreBtn" onClick={onHandleMoreContact}>
                <div className="proofAddMoreContent">
                    <img className="proofAddMoreIcon" alt="" src={icon_contact_add} />
                    <div className="proofAddMoreTitle">{`Every 2 additional contacts\n= 5%more approve rate.`}</div>
                </div>
            </div>

            <div className="proofApplyBtn" onClick={onHandleSubmit}>
                <div className="mainButtonGradient">Next</div>
            </div>

            <PrivacyPolicyLink pageTag={userStateInfo.pageTitle} showCheckbox={false} linkText="Privacy policy" />

            {/* <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} /> */}

            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div>
    )
}